<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>现代BBS评论系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#64748B',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .comment-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .reply-line {
                border-left: 2px solid #e2e8f0;
            }
            .btn-hover {
                @apply transition-all duration-200 hover:shadow-lg transform hover:-translate-y-0.5;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-comments text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">现代BBS评论系统</h1>
            </div>
            <div class="flex items-center space-x-4">
                {% if current_user %}
                    <span class="text-gray-700">欢迎，{{ current_user.username }}</span>
                    <a href="/logout" class="text-neutral hover:text-primary transition-colors">
                        <i class="fa fa-sign-out mr-1"></i>退出登录
                    </a>
                {% else %}
                    <a href="/login" class="text-neutral hover:text-primary transition-colors">
                        <i class="fa fa-sign-in mr-1"></i>登录
                    </a>
                    <a href="/register" class="bg-primary text-white px-3 py-1.5 rounded-lg hover:bg-primary/90 transition-colors">
                        注册
                    </a>
                {% endif %}
                <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-moon-o text-neutral"></i>
                </button>
            </div>
        </div>
    </header>
    
    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- 介绍区 -->
        <section class="mb-10 text-center">
            <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4">欢迎参与讨论</h2>
            <p class="text-neutral max-w-2xl mx-auto">在这里分享你的想法，参与有意义的讨论，尊重他人观点，共同维护友好的交流环境。</p>
        </section>
        
        <!-- 评论表单（仅登录用户显示） -->
        {% if current_user %}
            <section class="bg-white rounded-xl p-6 shadow-md mb-10 transform transition-all hover:shadow-lg">
                <h3 class="text-xl font-semibold mb-4 flex items-center text-gray-800">
                    <i class="fa fa-pencil-square-o text-primary mr-2"></i>发表评论
                </h3>
                <form id="commentForm" class="space-y-4">
                    <input type="hidden" id="authorId" value="{{ current_user.id }}">
                    <input type="hidden" id="parentId" value="">
                    <div>
                        <label for="content" class="block text-sm font-medium text-gray-700 mb-1">评论内容</label>
                        <textarea 
                            id="content" 
                            rows="4" 
                            required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all outline-none resize-none text-gray-800"
                            placeholder="分享你的想法..."
                        ></textarea>
                    </div>
                    <button 
                        type="submit" 
                        class="bg-primary text-white px-6 py-2.5 rounded-lg font-medium btn-hover flex items-center"
                    >
                        <i class="fa fa-paper-plane mr-2"></i>发布评论
                    </button>
                </form>
            </section>
        {% else %}
            <section class="bg-white rounded-xl p-6 shadow-md mb-10 text-center">
                <p class="text-neutral mb-4">请先<a href="/login" class="text-primary hover:underline">登录</a>或<a href="/register" class="text-primary hover:underline">注册</a>后发表评论</p>
                <a href="/login" class="inline-block bg-primary text-white px-6 py-2.5 rounded-lg font-medium btn-hover">
                    去登录
                </a>
            </section>
        {% endif %}
        
        <!-- 评论列表 -->
        <section>
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-comments-o text-primary mr-2"></i>评论列表
                </h3>
                <span id="commentCount" class="bg-gray-100 text-neutral px-3 py-1 rounded-full text-sm">{{ comments|length }} 条评论</span>
            </div>
            
            <div id="commentsContainer" class="space-y-6">
                <!-- 加载状态 -->
                <div id="loadingIndicator" class="flex justify-center py-10 hidden">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
                </div>
                
                <!-- 空状态 -->
                {% if comments|length == 0 %}
                    <div id="emptyState" class="text-center py-16">
                        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                            <i class="fa fa-comment-o text-2xl text-gray-400"></i>
                        </div>
                        <h3 class="text-lg font-medium text-gray-900 mb-1">暂无评论</h3>
                        <p class="text-neutral">成为第一个发表评论的人吧！</p>
                    </div>
                {% else %}
                    <!-- 循环渲染顶级评论 -->
                    {% for top_comment in comments if top_comment.parent_id == None %}
                        <!-- 传递当前评论到子模板 -->
                        {% with comment=top_comment %}
                            {% include "comment_item.html" %}
                        {% endwith %}
                    {% endfor %}
                {% endif %}
            </div>
        </section>
    </main>
    
    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-16">
        <div class="container mx-auto px-4 py-8 text-center text-neutral">
            <p>© 2025 现代BBS评论系统</p>
        </div>
    </footer>
    
    <!-- 通知组件 -->
    <div id="notification" class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50"></div>

    <script>
        // API基础URL
        const API_BASE_URL = '';
        
        // DOM元素
        const commentForm = document.getElementById('commentForm');
        const commentsContainer = document.getElementById('commentsContainer');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const emptyState = document.getElementById('emptyState');
        const commentCount = document.getElementById('commentCount');
        const notification = document.getElementById('notification');
        const themeToggle = document.getElementById('themeToggle');
        const currentUserId = {{ current_user.id if current_user else 'null' }};
        
        // 初始化
        // 初始化（删除模板语法判断，直接加载评论）
document.addEventListener('DOMContentLoaded', () => {
    loadComments(); // 无需判断模板变量，直接调用加载函数
    setupEventListeners();
});
        
        // 事件监听
        function setupEventListeners() {
            if (commentForm) {
                commentForm.addEventListener('submit', handleCommentSubmit);
            }
            themeToggle.addEventListener('click', toggleTheme);
            
            // 回复按钮事件
            document.querySelectorAll('.reply-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const commentId = btn.dataset.commentId;
                    const authorName = btn.dataset.authorName;
                    replyTo(commentId, authorName);
                });
            });
            
            // 删除按钮事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const commentId = btn.dataset.commentId;
                    const authorId = parseInt(btn.dataset.authorId);
                    if (currentUserId === authorId) {
                        deleteComment(commentId);
                    } else {
                        showNotification('没有权限删除他人评论', 'warning');
                    }
                });
            });
        }
        
        // 加载评论
       // 确保在页面加载时获取评论数据
let comments = []; // 先初始化变量

// 1. 加载评论（更新为正确逻辑）
async function loadComments() {
    try {
        showLoading();
        // 携带 session cookie，确保后端识别登录状态
        const response = await fetch(`${API_BASE_URL}/comments`, {
            credentials: 'include'
        });
        
        if (!response.ok) throw new Error(`加载失败，状态码: ${response.status}`);
        
        const commentsData = await response.json();
        comments = commentsData; // 更新全局数组
        renderComments(commentsData); // 调用渲染函数
        updateCommentCount(commentsData.length); // 更新评论数
        
        hideLoading();
    } catch (error) {
        console.error('加载评论出错:', error);
        showNotification('加载评论失败，请稍后重试', 'error');
        hideLoading();
        checkEmptyState(true); // 加载失败显示空状态
    }
}

// 页面加载完成后调用
document.addEventListener('DOMContentLoaded', () => {
                
            loadComments();
            setupEventListeners();
        });

        /*
        // 渲染评论
        function renderComments(comments) {

            commentsContainer.innerHTML = '';
            const topLevelComments = comments.filter(comment => comment.parent_id === null);
            
            if (topLevelComments.length === 0) {
                checkEmptyState(true);
                return;
            }
            
            topLevelComments.forEach(comment => {
                const commentElement = createCommentElement(comment, comments);
                commentsContainer.appendChild(commentElement);
            });
            setupEventListeners();
        }
        
function renderComments() {
  const commentList = document.getElementById('comment-list');
  if (!commentList) return;
  
  commentList.innerHTML = '';
  
  // 确保使用的是已经初始化的comments变量
  comments.forEach(comment => {
    // 渲染单个评论的逻辑
    const commentElement = document.createElement('div');
    commentElement.className = 'comment';
    commentElement.innerHTML = `
      <h4>${comment.author}</h4>
      <p>${comment.content}</p>
      <small>${new Date(comment.created_at).toLocaleString()}</small>
    `;
    commentList.appendChild(commentElement);
  });
}

*/



// 2. 渲染评论（整合逻辑，渲染到正确容器）
function renderComments(commentsData) {
    commentsContainer.innerHTML = ''; // 清空容器
    const topLevelComments = commentsData.filter(c => c.parent_id === null); // 筛选顶级评论
    
    if (topLevelComments.length === 0) {
        checkEmptyState(true); // 无评论显示空状态
        return;
    }
    
    checkEmptyState(false); // 有评论隐藏空状态
    // 渲染所有顶级评论
    topLevelComments.forEach(comment => {
        const commentElement = createCommentElement(comment, commentsData);
        commentsContainer.appendChild(commentElement);
    });
    setupEventListeners(); // 重新绑定按钮事件（动态元素需重新绑定）
}


        // 创建评论元素
        function createCommentElement(comment, allComments) {
            const div = document.createElement('div');
            div.className = 'bg-white rounded-xl p-6 comment-shadow transition-all duration-300 hover:shadow-lg';
            div.dataset.id = comment.id;
            
            const formattedDate = new Date(comment.created_at).toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            const formattedContent = comment.content.replace(/\n/g, '<br>');
            
            const deleteBtn = currentUserId === comment.author_id 
                ? `<button class="delete-btn text-neutral hover:text-red-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors" 
                           data-comment-id="${comment.id}" 
                           data-author-id="${comment.author_id}"
                           title="删除">
                       <i class="fa fa-trash-o"></i>
                   </button>` 
                : '';
            
            div.innerHTML = `
                <div class="flex justify-between items-start mb-3">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold mr-3">
                            ${comment.author.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <h4 class="font-medium text-gray-800">${comment.author}</h4>
                            <p class="text-sm text-neutral">${formattedDate}</p>
                        </div>
                    </div>
                    <div class="flex space-x-2">
                        <button class="reply-btn text-neutral hover:text-primary p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                                data-comment-id="${comment.id}"
                                data-author-name="${comment.author}"
                                title="回复">
                            <i class="fa fa-reply"></i>
                        </button>
                        ${deleteBtn}
                    </div>
                </div>
                <div class="mb-4">
                    <p class="text-gray-800">${formattedContent}</p>
                </div>
                <div class="replies pl-6 mt-4 space-y-4"></div>
            `;
            
            // 添加回复
            const repliesContainer = div.querySelector('.replies');
            const replies = allComments.filter(c => c.parent_id === comment.id);
            
            replies.forEach(reply => {
                const replyElement = createCommentElement(reply, allComments);
                replyElement.classList.add('reply-line');
                repliesContainer.appendChild(replyElement);
            });
            
            return div;
        }
        
       // 提交评论
// 处理评论提交（修复：提交成功后重新渲染评论，无需手动刷新）
async function handleCommentSubmit(e) {
    e.preventDefault();
    
    // 首先检查登录状态（前端双重校验）
    if (!currentUserId) {
        return showNotification('请先登录后再发表评论', 'warning');
    }
    
    const contentInput = document.getElementById('content');
    const parentIdInput = document.getElementById('parentId');
    
    const commentData = {
        content: contentInput.value.trim(),
        parent_id: parentIdInput.value ? parseInt(parentIdInput.value) : null
    };
    
    if (!commentData.content) {
        return showNotification('请输入评论内容', 'warning');
    }
    
    try {
        showLoading();
        
        const response = await fetch(`${API_BASE_URL}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                // 如需携带认证信息（如JWT），这里需要添加
                // 'Authorization': `Bearer ${getToken()}`
            },
            body: JSON.stringify(commentData),
            // 确保跨域请求携带认证信息
            credentials: 'include'
        });
        
        // 重点：区分不同错误状态码
        if (!response.ok) {
            if (response.status === 401) {
                // 未授权：登录状态失效
                return showNotification('登录状态已失效，请重新登录', 'error');
            } else if (response.status === 400) {
                // 请求参数错误
                const error = await response.json();
                return showNotification(error.detail || '评论内容不符合要求', 'error');
            } else {
                throw new Error('服务器错误，提交评论失败');
            }
        }
        
        // 提交成功：先重新获取所有评论
        const newCommentsRes = await fetch(`${API_BASE_URL}/comments`, { credentials: 'include' });
        if (!newCommentsRes.ok) throw new Error('获取最新评论失败');
        const newComments = await newCommentsRes.json();
        
        // 再处理UI更新（现在newComments已正确定义）
        commentForm.reset();
        parentIdInput.value = '';
        renderComments(newComments);
        updateCommentCount(newComments.length);
        checkEmptyState(newComments.length === 0);
        showNotification(commentData.parent_id ? '回复成功！' : '评论发表成功！', 'success');

    } catch (error) {
        console.error('提交评论时出错:', error);
        showNotification(error.message || '网络异常，请稍后重试', 'error');
    } finally {
        hideLoading();
    }
}
    


        // 回复功能
        function replyTo(commentId, authorName) {
            const parentIdInput = document.getElementById('parentId');
            const contentInput = document.getElementById('content');
            
            parentIdInput.value = commentId;
            contentInput.value = `@${authorName} `;
            contentInput.focus();
            commentForm.scrollIntoView({ behavior: 'smooth' });
        }
        
        // 删除评论
        async function deleteComment(commentId) {
            if (!confirm('确定要删除这条评论吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/comments/${commentId}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || '删除失败');
                }
                
                window.location.reload();
                showNotification('评论已删除', 'success');
                
            } catch (error) {
                console.error('删除评论时出错:', error);
                showNotification(error.message || '删除失败，请稍后重试', 'error');
            }
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            let bgColor, textColor, icon;
            switch (type) {
                case 'success':
                    bgColor = 'bg-green-500';
                    textColor = 'text-white';
                    icon = 'fa-check-circle';
                    break;
                case 'error':
                    bgColor = 'bg-red-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-circle';
                    break;
                case 'warning':
                    bgColor = 'bg-yellow-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-triangle';
                    break;
                default:
                    bgColor = 'bg-primary';
                    textColor = 'text-white';
                    icon = 'fa-info-circle';
            }
            
            notification.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50 ${bgColor} ${textColor}`;
            notification.innerHTML = `<i class="fa ${icon} mr-2"></i> ${message}`;
            
            setTimeout(() => {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
            }, 3000);
        }
        
        // 加载状态控制
        function showLoading() {
            loadingIndicator.classList.remove('hidden');
            if (emptyState) emptyState.classList.add('hidden');
        }
        function hideLoading() {
            loadingIndicator.classList.add('hidden');
        }
        function checkEmptyState(isEmpty) {
            if (emptyState) {
                emptyState.classList.toggle('hidden', !isEmpty);
            }
        }
        
        // 更新评论计数
        function updateCommentCount(count) {
            if (commentCount) commentCount.textContent = `${count} 条评论`;
        }
        
        // 主题切换
        function toggleTheme() {
            document.body.classList.toggle('bg-gray-900');
            document.body.classList.toggle('bg-gray-50');
            document.body.classList.toggle('text-white');
            document.body.classList.toggle('text-dark');
            
            const icon = themeToggle.querySelector('i');
            icon.classList.toggle('fa-moon-o');
            icon.classList.toggle('fa-sun-o');
        }
    </script>
</body>
</html>